﻿using Dapper;
using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Nova.Data.DbFactory;

namespace Nova.Data
{
    public class BaseRepository
    {
        private Database database = null;
        public BaseRepository(DatabaseType databaseType = DatabaseType.SqlServer)
        {
            database = CreateConnection(DbContext.ConnectionString, databaseType);
        }

        public Database GetConnection()
        {
            return database;
        }
        public void Dispose()
        {
            if (database != null)
            {
                database.Dispose();
            }
        }

        public int Execute(string sql, object param = null, IDbTransaction tran = null, int? commandTimeOut = null, CommandType? commandType = default(CommandType?))
        {
            return database.Connection.Execute(sql, param, tran, commandTimeOut, commandType);
        }

        public object ExecuteScalar(string sql, object param = null, IDbTransaction tran = null, int? commandTimeOut = null, CommandType? commandType = default(CommandType?))
        {
            return database.Connection.ExecuteScalar(sql, param, tran, commandTimeOut, commandType);
        }

        public T GetByCondition<T>(string sql, object param = null, IDbTransaction tran = null, int? commandTimeOut = null, CommandType? commandType = default(CommandType?)) where T : class
        {
            T entity = null;
            entity = database.Connection.Query<T>(sql, param, tran, true, commandTimeOut, commandType).FirstOrDefault();
            return entity;
        }

        public List<T> GetByConditionList<T>(string sql, object param = null, IDbTransaction tran = null, int? commandTimeOut = null, CommandType? commandType = default(CommandType?)) where T : class
        {
            return database.Connection.Query<T>(sql, param, tran, true, commandTimeOut, commandType).ToList();
        }

        public List<T> GetByStoredProcedureList<T>(string sql, object param = null) where T : class
        {
            return database.Connection.Query<T>(sql, param, commandType: CommandType.StoredProcedure).ToList();
        }
    }
}
